<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { InventoryReport } from '@/service/api/inventory';
import { useEcharts } from '@/hooks/common/echarts';
import { DateUtil } from '@/utils/dayjs';

const dataType = ref('num');

const dataTypeOptions = [
  { label: '按数量', value: 'num' },
  { label: '按金额', value: 'money' }
];

// 创建图表
const { domRef, updateOptions } = useEcharts(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    right: 20,
    top: 'center',
    width: 80,
    type: 'scroll',
    pageIconColor: '#aaa',
    pageIconInactiveColor: '#ddd',
    pageIconSize: 12,
    pageTextStyle: {
      color: '#666',
      fontSize: 10
    },
    textStyle: {
      fontSize: 10,
      color: '#666'
    },
    formatter(name: string) {
      return name.length > 10 ? `${name.substring(0, 10)}...` : name;
    }
  },
  series: [
    {
      name: '库存分布',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['30%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 8,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 14,
          fontWeight: 'bold'
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      labelLine: {
        show: false
      },
      data: [] as any[]
    }
  ]
}));

// 获取仓库分布数据
async function updateChartData() {
  try {
    const { year, month, day } = DateUtil.getTodayParts();

    const response = await InventoryReport.getStockNumMoney({
      year,
      month,
      day,
      dataType: dataType.value
    });

    if (response && !response.error && response.data) {
      // transformBackendResponse已经提取了data，直接使用
      const result = response.data;

      if (Array.isArray(result)) {
        // 预定义颜色
        const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#eb2f96', '#13c2c2', '#2f54eb'];

        // 处理API数据（根据原项目数据结构）
        const chartData = result.map((item: any, index: number) => ({
          name: item.name || item.stockName || `仓库${index + 1}`,
          value:
            dataType.value === 'num'
              ? item.allReserve || item.value || 0
              : item.allReserveMoney || item.money || item.value || 0,
          itemStyle: { color: colors[index % colors.length] }
        }));

        updateOptions(opts => {
          opts.series[0].data = chartData;
          opts.series[0].name = dataType.value === 'num' ? '库存数量' : '库存金额';
          return opts;
        });
      } else if (result && typeof result === 'object') {
        // 尝试从对象中提取数据
        const chartData: any[] = [];
        const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#eb2f96', '#13c2c2', '#2f54eb'];

        if (result.data && Array.isArray(result.data)) {
          result.data.forEach((item: any, index: number) => {
            chartData.push({
              name: item.name || item.stockName || `仓库${index + 1}`,
              value: item.value || item.num || item.money || 0,
              itemStyle: { color: colors[index % colors.length] }
            });
          });
        } else {
          // 如果是对象形式，尝试遍历key-value
          let index = 0;
          for (const key in result) {
            if (typeof result[key] === 'object' && result[key].value !== undefined) {
              chartData.push({
                name: result[key].name || key,
                value: result[key].value || 0,
                itemStyle: { color: colors[index % colors.length] }
              });
              index += 1;
            }
          }
        }

        if (chartData.length > 0) {
          updateOptions(opts => {
            opts.series[0].data = chartData;
            opts.series[0].name = dataType.value === 'num' ? '库存数量' : '库存金额';
            return opts;
          });
        } else {
          showEmptyDistributionChart();
        }
      } else {
        showEmptyDistributionChart();
      }
    } else {
      showEmptyDistributionChart();
    }
  } catch {
    // 错误处理 - 在生产环境中可以添加用户友好的提示
    showEmptyDistributionChart();
  }
}

// 显示空图表
function showEmptyDistributionChart() {
  updateOptions(opts => {
    opts.series[0].data = [];
    opts.series[0].name = dataType.value === 'num' ? '库存数量' : '库存金额';
    return opts;
  });
}

// 数据类型变化
function handleDataTypeChange() {
  updateChartData();
}

// 初始化数据 - 使用onMounted替代危险的setTimeout
onMounted(() => {
  updateChartData();
});
</script>

<template>
  <div class="h-full flex flex-col">
    <!-- 标题和控制 -->
    <div class="mb-3 flex items-center justify-between px-3">
      <div class="text-sm text-gray-700 font-medium">仓库库存分布</div>
      <div class="flex items-center">
        <NSelect
          v-model:value="dataType"
          size="small"
          class="w-[90px]"
          :options="dataTypeOptions"
          @update:value="handleDataTypeChange"
        />
      </div>
    </div>

    <!-- 图表容器 -->
    <div class="flex-1">
      <div ref="domRef" class="h-full min-h-[200px] w-full"></div>
    </div>
  </div>
</template>
